#include "sqlite.h"

/*1. 函数功能：创建打开数据库，建表*/
sqlite3* create_db_engine(const char *pdbfile){
    char sql[100] = "";
    char *perrmsg = NULL;
    sqlite3* pdb = NULL;
    int ret = 0;
    // 打开数据库
    ret = sqlite3_open(pdbfile,&pdb);
    if(ret != SQLITE_OK){
	    perrmsg = (char *)sqlite3_errmsg(pdb);
	    printf("open %s failed:%s\n","test.db",perrmsg);
	    sqlite3_close(pdb);
	    pdb = NULL;
	    return NULL;
    }    
    // 建user表
    sprintf(sql,"create table IF NOT EXISTS user(name char[20] PRIMARY KEY NOT NULL,password char[20],flag int)");
    ret = sqlite3_exec(pdb,sql,NULL,NULL,&perrmsg);
    if(ret != SQLITE_OK){
	    printf("exec %s failed: %s\n",sql,perrmsg);
	    sqlite3_free(perrmsg);
	    sqlite3_close(pdb);
	    pdb=NULL;
	    return NULL;
    }
    // 建history表
    sprintf(sql,"create table IF NOT EXISTS history(name char[20],word char[30],time char[20])");
    ret = sqlite3_exec(pdb,sql,NULL,NULL,&perrmsg);
    if(ret != SQLITE_OK){
	    printf("exec %s failed: %s\n",sql,perrmsg);
	    sqlite3_free(perrmsg);
	    sqlite3_close(pdb);
	    pdb=NULL;
	    return NULL;
    }
    
    return pdb;
}

/*2. 对sqllite3_exec的二次封装*/
int my_sqlite3_exec(sqlite3* pdb, const char *sql, sqlite3_callback callback, void*para, char** errmsg){
    int ret = 0;
    while(1){
        ret = sqlite3_exec(pdb,sql,callback,para,errmsg);
        if(ret == SQLITE_BUSY||ret == SQLITE_LOCKED){
            usleep(30* 1000);
            continue;
        }
        else    break;
    }
    return ret;
}

/*3. 对sqllite3_get_table的二次封装*/
int my_sqlite3_get_table(sqlite3 * db,const char *zSql,char ***pazResult,int *pnRow,int *pnColumn,char **pzErrmsg ){
    int ret = 0;
    while(1){
        ret = sqlite3_get_table(db,zSql,pazResult,pnRow,pnColumn,pzErrmsg);
        if(ret ==SQLITE_BUSY||ret==SQLITE_LOCKED){
            usleep(30*1000);
            continue;
        }
        else    break;
    };
    return ret;
}

/*4. destroy_db_engine*/
void destory_db_engine(sqlite3 *pdb){
    sqlite3_close(pdb);    
}